package com.xbenben.project.common.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.Future;
import java.util.function.Function;

/**
 * @author yu.zhijia
 * Date:2023/6/26 10:32
 **/

@Component
@Slf4j
public class TaskUtils {

    private static ThreadPoolTaskExecutor treadPoolTaskExecutorStatic;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public static <V, T> List<V> asyncExecuteAndGetList(List<T> params, Function<T, V> callable) {
        List<Future<V>> futures = Lists.newArrayList();
        for (T param : params) {
            Future<V> future = treadPoolTaskExecutorStatic.submit(() -> callable.apply(param));
            futures.add(future);
        }
        List<V> results = Lists.newArrayList();
        try {
            for (Future<V> future : futures) {
                while (true) {
                    if (future.isDone() && !future.isCancelled()) {
                        V result = future.get();
                        if (result != null) {
                            results.add(result);
                        }
                        break;
                    } else {
                        Thread.sleep(100);
                    }
                }
            }
        } catch (Exception e) {
            log.error("多线程异步获取结果失败！", e);
            return null;
        }
        return results;
    }

    @PostConstruct
    public void init() {
        log.info("threadPoolTaskExecutor: {}", JSON.toJSONString(threadPoolTaskExecutor));
        treadPoolTaskExecutorStatic = threadPoolTaskExecutor;
    }

}



